# -*- coding: utf-8 -*-
"""
Created on Wed Aug  8 16:59:37 2018

@author: jiujiujiu

读币网
http://www.dubiwang.com/

"""
import requests
import re
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_Kxun(url, data):
    dates = []
    text = get_html_text(url, data)
    if not text:
        return None
    regex = re.compile(r'<span class="lst-time">&nbsp;([\s\S]*?)</span>')
    dates = re.findall(regex, text)
    return dates


def count_process():
    a = 1
    dates = []
    while a < 80:
        data = {
            'page': a
        }
        url = 'http://www.dubiwang.com/news/index'
        date = get_dates_Kxun(url, data)
        if not date:
            break
        dates += date
        print('----读币网获取第{}页----'.format(a))
        a += 1
    return dates


def count_process_one():  # 快讯
    u = '读币网'
    d1 = 0
    d2 = 0
    d3 = 0
    a = 0
    b = 0
    l = []
    dates = count_process()
    try:
        while b < 3:
            if dates[a] < dates[a + 1]:
                l.append(a + 1)
                b += 1
            a += 1
        d1 = len(dates[:l[0]])
        d2 = len(dates[l[0]:l[1]])
        d3 = len(dates[l[1]:l[2]])
        return (d1, d2, d3)
    except:
        return (d1, d2, d3)


def main():
    u = '读币网'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
